package icu.wdtt.service.Impl;

import icu.wdtt.mapper.AuthorityMapper;
import icu.wdtt.mapper.RoleMapper;
import icu.wdtt.model.Authority;
import icu.wdtt.model.Role;
import icu.wdtt.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class RoleServiceImpl implements RoleService {


    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AuthorityMapper authorityMapper;
    @Override
    public List<Role> getAll() {
        try {
            List<Role> roleList = roleMapper.getAll();
            return roleList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Role get(int rid) {
        try {
            Role role = roleMapper.get(rid);
            return role;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Boolean add(Role role) {
        try {
            roleMapper.add(role);
            if(role.getRid() > 0){
                for (Authority authority : role.getAuthorityList()) {
                   roleMapper.addRoleAndAuthority(role.getRid(),authority.getAid());
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean del(int rid) {
        try {
            roleMapper.delRoleAndAuthority(rid);
            roleMapper.delRoleAndUser(rid);
            roleMapper.del(rid);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean update(Role role) {
            try {
                roleMapper.update(role);
                roleMapper.delRoleAndAuthority(role.getRid());
                role.getAuthorityList().forEach(a->roleMapper.addRoleAndAuthority(role.getRid(),a.getAid()));
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        return false;
    }

}
